package main

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"regexp"

	"github.com/astaxie/beego/config"
	"github.com/go-zoox/fetch"
	"github.com/tidwall/gjson"
)

func main() {
	argsWithoutProg := os.Args[1:]

	configFilePath := "/etc/triton/config.conf"
	if len(argsWithoutProg) > 0 {
		configFilePath = argsWithoutProg[0]
	}

	cnf, err := config.NewConfig("ini", configFilePath)

	if err != nil {
		panic("config.conf file miss")
	}

	cnfBaseUrl := "http://" + cnf.String("domain") + "/"
	fetchClient := fetch.Create(cnfBaseUrl)

	resp1, err := fetchClient.SetURL("/login").SetConfig(&fetch.Config{
		Proxy: cnf.String("proxy"), //"http://127.0.0.1:17890",
		Headers: map[string]string{
			"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47",
			"Origin":     cnfBaseUrl,
			"Referer":    cnfBaseUrl + "/login",
		},
	}).Execute()

	if err != nil {
		fmt.Println(err.Error())
		panic(err)
	}
	cookieValue := resp1.SetCookie()

	fmt.Println(cookieValue)

	// fetchClient = fetchClient.Clone()

	//.SetHeader("Cookie", cookieValue)
	resp2, err := fetchClient.SetURL("/user-login-auth").SetConfig(&fetch.Config{
		Method: "POST",
		Proxy:  cnf.String("proxy"), //"http://127.0.0.1:17890",
		Headers: map[string]string{
			"User-Agent":   "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47",
			"Origin":       cnfBaseUrl,
			"Referer":      cnfBaseUrl + "/login",
			"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			"Cookie":       cookieValue,
		},

		Body: map[string]string{
			"param[UserName]": cnf.String("username"),
			"param[UserPswd]": cnf.String("password"),
			"uri":             "id=&url=&user=&mac=",
			"force":           "0",
		},
	}).Execute()

	if err != nil {
		panic(err)
	}

	resp2Json, err := resp2.JSON()
	if err != nil {
		fmt.Println(string(resp2.Body), err)
	} else if gjson.Get(resp2Json, "status").Str != "1" {
		panic(resp2Json)
	}

	user_name, _ := url.QueryUnescape(gjson.Get(resp2Json, "user_name").Str)

	resp3, err := fetchClient.SetURL("/logout").SetConfig(&fetch.Config{
		Method: "GET",
		Params: map[string]string{
			"user_name": user_name,
		},
		Proxy: cnf.String("proxy"), //"http://127.0.0.1:17890",
		Headers: map[string]string{
			"User-Agent":   "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47",
			"Origin":       cnfBaseUrl,
			"Referer":      cnfBaseUrl + "/login",
			"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
			"Cookie":       cookieValue,
		},
	}).Execute()

	if err != nil {
		panic(err)
	}

	resp3Str := string(resp3.Body)
	rgx := regexp.MustCompile(`\{\s*user_name\:\s*"(.+?)"\s*,\s*login_ip\:\s*"(.+?)"\s*\}`)
	userIpJson := rgx.FindString(resp3Str)
	if len(userIpJson) == 0 {
		panic("不能找到用户登录用的IP")
	}

	matchs := rgx.FindStringSubmatch(userIpJson)
	user_name = matchs[1]
	login_ip := matchs[2]

	log.Printf("%s login ip is %s", user_name, login_ip)
	//ws_keep(cnf, user_name, login_ip, cookieValue)

}

// func ws_keep(cnf config.Configer, userName, loginIp, cookieValue string) {
// 	domain := cnf.String("domain")
// 	cnfBaseUrl := "http://" + domain
// 	// wsUrl := "ws://" + domain + "/go-ws/user-auth"
// 	// var addr = flag.String("addr", wsUrl, "http service address")
// 	flag.Parse()
// 	log.SetFlags(0)

// 	interrupt := make(chan os.Signal, 1)
// 	signal.Notify(interrupt, os.Interrupt)

// 	u := url.URL{Scheme: "ws", Host: domain, Path: "/go-ws/user-auth"}
// 	log.Printf("connecting to %s", u.String())

// 	c, _, err := websocket.DefaultDialer.Dial(u.String(), http.Header{
// 		"User-Agent": {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47"},
// 		"Origin":     {cnfBaseUrl},
// 		"Referer":    {cnfBaseUrl + "/login"},
// 		"Cookie":     {cookieValue},
// 	})

// 	if err != nil {
// 		log.Fatal("dial:", err)
// 	}
// 	defer c.Close()

// 	done := make(chan struct{})

// 	go func() {
// 		defer close(done)
// 		for {
// 			_, message, err := c.ReadMessage()
// 			if err != nil {
// 				log.Println("read:", err)
// 				return
// 			}
// 			log.Printf("%s recv: %s", time.Now(), message)
// 		}
// 	}()

// 	for {
// 		select {
// 		case <-done:
// 			return

// 		case <-interrupt:
// 			log.Println("interrupt")

// 			// Cleanly close the connection by sending a close message and then
// 			// waiting (with timeout) for the server to close the connection.
// 			err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
// 			if err != nil {
// 				log.Println("write close:", err)
// 				return
// 			}
// 			select {
// 			case <-done:
// 			case <-time.After(time.Second):
// 			}
// 			return
// 		}
// 	}
// }
